package com.yz.jdd.module.login.view;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.utils.AppUtils;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.main.MainActivity;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.request.Request_Magic;
import com.yz.jdd.network.request.Request_UserLogin;
import com.yz.jdd.network.response.Response_UserLogin;
import com.yz.jdd.widget.TimerButton;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActvity extends BaseActivity {

    @BindView(R.id.top_back)
    TextView topBack;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_right)
    TextView topRight;
    @BindView(R.id.edit_phone)
    EditText editPhone;

    @BindView(R.id.text_phone)
    EditText textPhone;

    @BindView(R.id.edit_verification_code)
    EditText editVerificationCode;

    @BindView(R.id.tv_get_code)
    TimerButton tvGetCode;

    @BindView(R.id.btn_login)
    Button btnLogin;

    private int timeLength = 60;
    private Request_UserLogin request_userLogin;
    private String myAccount;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_actvity);
        ButterKnife.bind(this);
        topTitle.setText("");
        topBack.setText("返回");
//        btnLogin.setEnabled(false);
        request_userLogin= (Request_UserLogin) getIntent().getSerializableExtra("request");
        myAccount=request_userLogin.getAccount();

        textPhone.setText(myAccount);

    }

    /**
     * 获取验证码
     *
     * @param
     */
    private void doSendVerify() {
        showLoading("正在发送验证码...");
        Map<String, String> params  = new HashMap<String, String>();
//        request.setWhiteMobile(myAccount);
        params.put("mm",myAccount);

        NetWorkRequset.sendMagicVerifyCode(params, new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                dismissLoading();
                tvGetCode.startTimer();
                Toast.makeText(LoginActvity.this, "验证码已发送", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onNeedLogin(String msg) {
                dismissLoading();
            }

            @Override
            public void onFail(Response_Base response_baseModel) {
                dismissLoading();
                if (!TextUtils.isEmpty(response_baseModel.getMsg())) {
                    Toast.makeText(LoginActvity.this, response_baseModel.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void  doMagicLogin(String phoneShop,String verifyCode){

        request_userLogin.setMm(myAccount);
        request_userLogin.setAccount(phoneShop);
        request_userLogin.setVerifyCode(verifyCode);

        NetWorkRequset.magicLogin(request_userLogin, new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                //返回权限以及user
                dismissLoading();
                Response_UserLogin response = (Response_UserLogin) response_baseModel.getResultObject();
                if (response != null) {
                    PreferencesUtils.putString(
                            MyApplication.application,
                            BaseConfigs.PREF_USERNAME, response.getUserName());

                    PreferencesUtils.putString(
                            MyApplication.application,
                            BaseConfigs.PREF_SHOPNAME, response.getShopName());

                    PreferencesUtils.putBoolean(MyApplication.application, BaseConfigs
                            .PREF_VERIFICATION_FLAG, response.isVerificationFlag());

                    PreferencesUtils.putString(MyApplication.application, BaseConfigs
                            .STRING_ROUTERCODE, response.getRouterCode());

                    PreferencesUtils.putString(MyApplication.application, BaseConfigs
                            .POS_SUPPLIERCODE, response.getSupplierCode());


                    String sessionId = response.getSessionId();
                    if (!TextUtils.isEmpty(sessionId)) {

                        PreferencesUtils.putString(
                                MyApplication.application,
                                BaseConfigs.PREF_SESSIONID, sessionId);
                    }
                    String shopId = response.getShopId();
                    if (!TextUtils.isEmpty(shopId)) {
                        PreferencesUtils.putString(
                                MyApplication.application,
                                BaseConfigs.PREF_SHOPID, shopId);
                    }
                    String regionName = response.getRegionName();
                    PreferencesUtils.putString(MyApplication.application,
                            BaseConfigs.STRING_REGIONNAME, regionName);

                    if (response.getMenuInfo() != null) {
                        PreferencesUtils.putString(
                                MyApplication.application,
                                BaseConfigs.PREF_MENUINFO, new Gson().toJson(response.getMenuInfo()));
                    }
                    String rc = response.getRc();
                    if (!TextUtils.isEmpty(rc)) {

                        PreferencesUtils.putString(
                                MyApplication.application,
                                BaseConfigs.STRING_ROUTE_CODE, rc);
                    }

                    Intent intent = new Intent(LoginActvity.this, MainActivity.class);
                    startActivity(intent);
                    LoginActvity.this.finish();
                }
            }

            @Override
            public void onNeedLogin(String msg) {

            }

            @Override
            public void onFail(Response_Base response_baseModel) {

            }
        });
    }



    @OnClick({R.id.top_back, R.id.tv_get_code, R.id.btn_login})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.top_back:
                finish();
                break;
            case R.id.tv_get_code:
                //需要判断 用户手机
                doSendVerify();

                break;
            case R.id.btn_login:
                String phoneShop = editPhone.getText().toString();
                if (checkPhoneNumber(phoneShop)) {
                    String verifyCode=editVerificationCode.getText().toString();
                    if(!TextUtils.isEmpty(verifyCode)){
                        doMagicLogin(phoneShop,verifyCode);
                    }else{
                        showToast("请输入验证码");
                    }

                }

                break;
        }
    }


    /**
     * 检查手机号码
     *
     * @param phoneNumber 手机号码
     */
    private boolean checkPhoneNumber(String phoneNumber) {
        boolean isPhoneNumber = false;
        if (TextUtils.isEmpty(phoneNumber)) {
            Toast.makeText(this, "请填写手机号", Toast.LENGTH_SHORT).show();
        } else if (phoneNumber.length() < 11) {
            Toast.makeText(this, "请填写有效的手机号", Toast.LENGTH_SHORT).show();
        } else if (!Pattern.matches("^(0|86|17951)?(1[0-9])[0-9]{9}$", phoneNumber)) {
            Toast.makeText(this, "请填写有效的手机号", Toast.LENGTH_SHORT).show();
        } else {
            isPhoneNumber = true;
        }
        return isPhoneNumber;
    }
}
